// 

function byId(x) {
  return document.getElementById(x);
}

function SimpleTable() {
  var html = "<div>";
  this.addRow = function(row) {
    html += "<div class='listitemchk'>" +
      row +
      "</div><div class='listdivi'></div>";
  };
  this.addPersonRow = function(person, row) {
    this.addRow(
      "<img class='listimg' src='" + person.getField("picture") + "'/>" +
      "<h3 class='smller'>" + person.getDisplayName() + "</h3>" +
      "<div class='para'>" +
      row +
      "</div>"
    );
  };
  this.getHtml = function() {
    return html + "</div>";
  };
}

var MyApp = function() {};

MyApp.render = function(data) {
  this.data = data;
  byId("main").innerHTML = "testing";
}

function getSurface() {
  return document.location.toString().match(/mode=canvas/) ? "canvas" : "profile";
}

function myInit() {
  var mode = (getSurface() == "canvas") ? "VIEWER" : "OWNER";
  if (1) {
    SocialNorms.createSocialAppOnLoad({
      render: function(data) {
        Gadgets[gadgetToLoad](data);
      },
    }, mode, ["gifts"]);
  }
}
myInit();

Gadgets = {};

Gadgets.hello = function(data) {
  byId("main").innerHTML =
    "Welcome, " + data.getViewer().getDisplayName();
}

Gadgets.friends = function(data) {
  var html = "Welcome, " + data.getViewer().getDisplayName();
  var table = new SimpleTable();
  var friends = data.getViewerFriends().asArray();
  for (var i=0; i<friends.length; i++) {
    table.addPersonRow(friends[i], "hi there");
  }
  html += table.getHtml();
  byId("main").innerHTML = html;
}

function makeOptions(person, val, fname) {
  var options = [["yugo", "a '86 Yugo"],
                 ["macbook", "a new MacBook Pro"],
                 ["lint", "a piece of lint"],
                 ["iphone", "an iPhone"]];
  var html = "<select onchange='" + fname + "(\"" + person.getId() + "\", \"" + person.getDisplayName() + "\", this)'>";
  for (var i=0; i<options.length; i++) {
    html += "<option value='" + options[i][0] + "'";
    if (val == options[i][0]) {
      html += " selected='selected'";
    }
    html += ">" + options[i][1] + "</option>";
  }
  html += "</select>";
  return html;
}

var globalGiftsGiven = {};

function handleChange1(id, name, sel) {
  var item = sel.options[sel.selectedIndex].value;
  globalGiftsGiven[id] = item;
  var json = globalGiftsGiven.toJSONString();
  var req = opensocial.newDataRequest();
  req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'gifts', json));
  console.log("setting: " + json);
  req.send();
}

function safeParseJSON(str) {
  if (!str) {
    return {};
  }
  try {
    return str.parseJSON();
  } catch (e) {
    console.log("error parsing JSON: " + e);
    return {};
  }
}

Gadgets.gifts = function(data) {
  var html = "Welcome, " + data.getViewer().getDisplayName();
  var table = new SimpleTable();
  var friends = data.getViewerFriends().asArray();

  globalGiftsGiven = safeParseJSON(data.getDataFor('VIEWER')['gifts']);

  for (var i=0; i<friends.length; i++) {
    var person = friends[i];
    var row = "You gave: " + makeOptions(person, globalGiftsGiven[person.getId()], 'handleChange1');
    table.addPersonRow(person, row);
  }
  html += table.getHtml();
  byId("main").innerHTML = html;
}

function handleChange2(id, name, sel) {
  handleChange1(id, name, sel);

  var stream = opensocial.newStream("main", "gift stream");
  var item = sel.options[sel.selectedIndex].value;
  var text = "a " + item + " to " + name;
  var activity = opensocial.newActivity(
    stream,
    theApp.data.getViewer().getDisplayName() + " gave a " + item + " to " + name
  );
  opensocial.requestCreateActivity(activity, "HIGH");
}

Gadgets.activities = function(data) {
  var html = "Welcome, " + data.getViewer().getDisplayName();
  var table = new SimpleTable();
  var friends = data.getViewerFriends().asArray();

  globalGiftsGiven = safeParseJSON(data.getDataFor('VIEWER')['gifts']);

  for (var i=0; i<friends.length; i++) {
    var person = friends[i];
    var row = "You gave: " + makeOptions(person, globalGiftsGiven[person.getId()], 'handleChange2');
    table.addPersonRow(person, row);
  }
  html += table.getHtml();
  byId("main").innerHTML = html;
}

Gadgets.profile = function(data) {
  if (getSurface() == "canvas") {
    Gadgets.activities(data);
  } else {
    var html = "Gifts you're receiving:";
    var table = new SimpleTable();
    var friends = data.getOwnerFriends().asArray();
    for (var i=0; i<friends.length; i++) {
      var person = friends[i];
      console.log(person.getDisplayName() + " => " + data.getDataFor(person).toJSONString());
      var friendGiftsGiven = safeParseJSON(data.getDataFor(person)['gifts']);
      var giftToOwner = friendGiftsGiven[data.getOwner().getId()];
      if (!giftToOwner) {
        continue;
      }
      var row = person.getDisplayName() + " gave you a " + giftToOwner;
      table.addPersonRow(person, row);
    }
    html += table.getHtml();
    byId("main").innerHTML = html;
  }
}
